package JUC;


import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @author 豆包LU
 * @date 2023/5/6 14:59
 */
public class AtomicStampedReferenceDemo {
    public static void main(String[] args) {
        // 初始化一个共享变量的值为 "A"，版本号为 1
        String initialRef = "A";
        int initialStamp = 1;
        AtomicStampedReference<String> atomicStampedReference = new AtomicStampedReference<>(initialRef, initialStamp);

        // 创建一个线程修改共享变量的值和版本号
        Thread thread1 = new Thread(() -> {
            // 获取共享变量的值和版本号
            int stamp = atomicStampedReference.getStamp();
            String reference = atomicStampedReference.getReference();

            // 模拟修改共享变量的值和版本号
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String newReference = "B";
            int newStamp = stamp + 1;

            // 使用 CAS 操作修改共享变量的值和版本号
            atomicStampedReference.compareAndSet(reference, newReference, stamp, newStamp);
        });

        // 创建一个线程使用 CAS 操作修改共享变量的值
        Thread thread2 = new Thread(() -> {
            // 获取共享变量的值和版本号
            String reference = atomicStampedReference.getReference();
            int stamp = atomicStampedReference.getStamp();

            // 模拟共享变量的值发生了 ABA 变化
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String newReference = "A";
            int newStamp = stamp + 1;

            // 使用 CAS 操作修改共享变量的值，此时因为版本号不相等，CAS 操作会失败
            boolean result = atomicStampedReference.compareAndSet(reference, newReference, stamp, newStamp);
            System.out.println("CAS result: " + result);
        });

        // 启动线程执行操作
        thread1.start();
        thread2.start();
    }
}

